const express = require("express");
const apiRouter = express.Router();
const OpenAI = require("openai");
const showdown = require("showdown");
const writeData = require("../db/module/writeData");
const readData = require("../db/module/readData");
const openai = new OpenAI({
  apiKey: global.config.openAI.apiKey,
  baseURL: global.config.openAI.baseURL,
});
const { v4: uuidv4 } = require("uuid");

// 豆包模型
apiRouter.post("/douBao", async (req, res) => {
  try {
    const { sessionId, text, modelType, id, messages } = req.body;

    // 存储每个用户的对话历史

    // 会话id ， 如果前端没有传过来的话 后端自己补充一个默认的id
    const session = sessionId || "defaultSession";

    // 设置 stream 参数为 true 开启流式响应
    const stream = await openai.chat.completions.create({
      messages,
      model: global.config.openAI.model,
      stream: true,
      reasoning_effort: "medium",
    });

    // 设置响应头，以支持流式响应
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    });

    let fullResponse = "";
    let parsedMarkdown = "";
    // 监听流数据
    for await (const part of stream) {
      const delta = part.choices[0].delta?.content;
      if (delta) {
        fullResponse += delta;
        const converter = new showdown.Converter();
        parsedMarkdown = converter.makeHtml(fullResponse);
        // 将数据发送给客户端
        global.sendMessageToUser(req.body.userId, delta);
        res.write(delta);
      }
    }
    res.end(
      JSON.stringify({
        code: 20000,
        msg: "发送成功",
      })
    );
  } catch (error) {
    console.error(error);
    res.send({
      code: 50000,
      msg: "操作失败",
      data: null,
    });
  }
});

// 返回历史对话记录
apiRouter.post("/getHistory", async (req, res) => {
  const { sessionId } = req.body;

  // 存储每个用户的对话历史

  // 会话id ， 如果前端没有传过来的话 后端自己补充一个默认的id
  const session = sessionId || "defaultSession";
  let messages = [];
  let id = "";
  // 通过sessionId查询历史对话记录
  let result = await readData({ sessionId: session }, "open_ai_history");

  if (result.code == 20000 && result.data.length != 0) {

    messages = JSON.parse(result.data[0].messages);
    id = result.data[0].id || "";
  }

  if (!id) {
    id = uuidv4();
  }

  res.send({
    code: 20000,
    msg: "操作成功",
    data: {
      id,
      messages,
    },
  });
});

// 存储对话历史
apiRouter.post("/saveHistory", async (req, res) => {
  try {
    const { sessionId, modelType, id, messages } = req.body;

    // 存储或者修改
    let result = await writeData(
      {
        sessionId: sessionId || "defaultSession",
        messages: JSON.stringify(messages),
        id: id,
        modelType: modelType || global.config.openAI.modelName,
      },
      "open_ai_history"
    );


    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 获取所有历史对话
apiRouter.post("/getAllHistory", async (req, res) => {
  try {
    let parmse = req.body;
    let result = await readData(parmse, "open_ai_history");
    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

module.exports = apiRouter;
